<!--
这个页面目前只用作以下按钮的展示

viewState:productionPool        生产中心>生产单池(产品列表)
viewState:inProduction          生产中心>进行中生产单(产品列表)
viewState:orderMaterialCommon   四类仓库>待入库采购单/已入库采购单(入库记录) 该页面状态作为通用的显示
-->

<template>
	<a-modal :title="title || '管理物料'" :width="1200" :visible="visible" :confirmLoading="confirmLoading" :footer="null"
		@ok="handleSubmit" @cancel="handleCancel">
		<a-card :bordered="false">
			<div class="table-page-search-wrapper">
				<a-form layout="inline">
					<a-row :gutter="48">

						<a-col :md="8" :sm="24" v-if="false">
							<a-form-item label="订单ID">
								<a-input v-model="queryParam.orderId" placeholder="请输入订单ID" />
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="table-operator">
				<a-button v-if="viewState == 'productionPool'" icon="plus" type="primary"
					@click="$refs.productAddForm.add(emsOrder)">新增产品
				</a-button>
				<a-button v-if="viewState == 'inProduction'" type="primary" @click="handleCompleteProduction">完成生产
				</a-button>
			</div>

			<s-table ref="table" size="default" :columns="columnsDynamic" :data="loadData" :alert="true"
				:rowKey="(record) => record.code" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
				:showPagination="false">
				<span slot="remark" slot-scope="text, record">
					<a-tooltip placement="topLeft" :title="record.material.remark">
						{{ record.material.remark }}
					</a-tooltip>
				</span>
				<template slot="extend1" slot-scope="text, record">
					{{ record.material ? record.material.extend1 : '' }}
				</template>
				<template slot="extend3" slot-scope="text, record">
					{{ record.material ? record.material.extend3 : '' }}
				</template>
				<template slot="materialModelNumber" slot-scope="text, record">
					{{ record.material ? record.material.materialModelNumber : '' }}
				</template>
				<!-- <span slot="image" slot-scope="text">
							<image-preview :images="text" />
            </span> -->
				<span slot="image" slot-scope="text,record">
					<image-preview1 :images="text" :imageUrl="record.imageUrl" />
				</span>
				<template slot="thisCompleteNumber" slot-scope="text, record">
					<a-input-number v-model:value="record.thisCompleteNumber" :step="1" :min="0" style="width: 67px;" />
				</template>

				<span slot="actionCommon" slot-scope="text, record" v-if="extra.title != '采购单入库记录'">
					<!--    查进度明细时，需要筛选出源引过该记录的订单      -->
					<a v-if="extra.title != '入库记录'" @click="$refs.orderIndexModal.show(Object.assign({ sourceOrderMaterialIds: record.orderMaterialId }, record),
						'订单列表', 'common')">进度明细</a>

					<!--    UI上显示的是订单物料列表,而不是订单.因此还要循环用一下本页面      -->
					<a v-else @click="$refs.orderMaterialIndexModal.show(
						{
							sourceOrderMaterialId: record.orderMaterialId,
							orderType: $businessEnum.ORDER_TYPE_ENUM.inOrder.id
						},
						{ title: '采购单入库记录', viewState: 'orderMaterialCommon' })">进度明细</a>
				</span>

				<span slot="action" slot-scope="text, record">
					<a @click="$refs.editForm.edit(record)">产品编辑</a>
					<!--          <a-divider type="vertical"/>-->
					<!--          <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">-->
					<!--            <a>删除</a>-->
					<!--          </a-popconfirm>-->
				</span>

				<span slot="actionInProduction" slot-scope="text, record">
					<a @click="$refs.productDetailForm.disabledShow(record)">产品明细</a>
				</span>
			</s-table>

			<!--      <add-form ref="addForm" @ok="handleOk"/>-->
			<edit-form ref="editForm" @ok="handleOk" />
			<ems-material-index1 ref="emsMaterialIndex1" :on-row-selected="onEmsMaterialIndex1Selected" />
			<product-add-form ref="productAddForm" @ok="handleOk" />
			<product-edit-form ref="productEditForm" @ok="handleOk" />
			<product-detail-form ref="productDetailForm" @ok="handleOk" />
			<order-index-modal ref="orderIndexModal" @ok="handleOk" />

			<!--  关联物料页面  -->
			<order-material-index-modal ref="orderMaterialIndexModal" @ok="handleOk" />

		</a-card>
	</a-modal>
</template>

<script>
import { STable } from '@/components'
import { page, del, add } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import { handleProductionOrderProductComplete } from '@/api/modular/main/emsorder/emsOrderManage'
// import addForm from '../emsordermaterial/emsOrderMaterialAddForm'
import editForm from '@/views/main/emsordermaterial/emsOrderMaterialEditForm'
import materialForm from '@/views/main/emsmaterial/emsMaterialIndex'
import emsMaterialIndex1 from '@/views/main/emsmaterial/emsMaterialIndex1'
import productAddForm from '@/views/main/emsorder/emsOrderProductAddForm'
import productEditForm from '@/views/main/emsorder/emsOrderProductEditForm'
import productDetailForm from '@/views/main/emsorder/emsOrderProductDetailForm'
import orderIndexModal from '@/views/main/emsorder/emsOrderIndexModal'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
	components: {
		STable,
		// addForm,
		editForm,
		materialForm,
		emsMaterialIndex1,
		productAddForm,
		productEditForm,
		productDetailForm,
		orderIndexModal,
		// 为了解决与该控件的循环引用,所以使用如下方法
		orderMaterialIndexModal: () => import('@/views/main/emsordermaterial/emsOrderMaterialIndexModal'),
	},

	data() {
		return {
			title: null,
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {},  // 查询参数
			// 加载数据方法 必须为 Promise 对象
			loadData: parameter => {
				return page(Object.assign(parameter, this.queryParam)).then((res) => {
					res.data.rows.forEach(value => {
						value.thisCompleteNumber = 0
					})
					return res.data
				})
			},
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			visible: false,
			confirmLoading: false,
			emsOrder: null,
			viewState: '',
			extra: {},
		}
	},
	computed: {
		token() {
			return Vue.ls.get(ACCESS_TOKEN)
		},
		columnsDynamic() {
			let vs = this.viewState
			if (vs == 'productionPool') {
				// 生产单池中(生产单草稿阶段)
				this.advanced = false
				return [
					{
						title: '产品编号',
						dataIndex: 'materialName'
					},
					{
						title: '产品别名',
						dataIndex: 'materialCode'
					},
					{
						title: '需求数',
						dataIndex: 'number'
					},
					{
						title: '序号', width: '80px',
						dataIndex: 'extend1'
					},
					{
						title: '软件版本号',
						dataIndex: 'extend2'
					},
					{
						title: '更新时间',
						dataIndex: 'updateTime'
					},
					{
						title: '备注',
						dataIndex: 'remark',
						ellipsis: true,
						scopedSlots: { customRender: 'remark' }
					},
					{
						title: '操作',
						dataIndex: 'action',
						width: '150px',
						scopedSlots: { customRender: 'action' }
					}
				]
			} else if (vs == 'inProduction') {
				// 生产单进行中
				this.advanced = true
				return [
					{
						title: '序号', width: '80px',
						customRender: (text, record, index) => `${index + 1}`
					},
					{
						title: '产品名称',
						dataIndex: 'materialName'
					},
					{
						title: '生产数量',
						dataIndex: 'number'
					},
					{
						title: '完成数量',
						dataIndex: 'completedNumber'
					},
					{
						title: '待生产数量',
						dataIndex: '',
						customRender: (text, record, index) => `${record.number - record.completedNumber}`
					},
					{
						title: '本次完成生产数量',
						scopedSlots: { customRender: 'thisCompleteNumber' }
					},
					{
						title: '已入库数量',
						dataIndex: 'inStoreNumber'
					},
					{
						title: '待入库数量',
						customRender: (text, record, index) => `${record.completedNumber - record.inStoreNumber}`
					},
					{
						title: '序号', width: '80px',
						dataIndex: 'extend1'
					},
					{
						title: '软件版本号',
						dataIndex: 'extend2'
					},
					{
						title: '备注',
						dataIndex: 'remark',
						ellipsis: true,
						scopedSlots: { customRender: 'remark' }
					},
					{
						title: '操作',
						width: '150px',
						scopedSlots: { customRender: 'actionInProduction' }
					}
				]
			} else if (vs == 'productionCompleted') {
				return [
					{
						title: '序号', width: '80px',
						customRender: (text, record, index) => `${index + 1}`
					},
					{
						title: '产品名称',
						dataIndex: 'materialName'
					},
					{
						title: '生产数量',
						dataIndex: 'number'
					},
					{
						title: '完成数量',
						dataIndex: 'completedNumber'
					},
					{
						title: '已入库数量',
						dataIndex: 'inStoreNumber'
					},
					{
						title: '待入库数量',
						customRender: (text, record, index) => `${record.completedNumber - record.inStoreNumber}`
					},
					{
						title: '序号', width: '80px',
						dataIndex: 'extend1'
					},
					{
						title: '软件版本号',
						dataIndex: 'extend2'
					},
					{
						title: '备注',
						dataIndex: 'remark',
						ellipsis: true,
						scopedSlots: { customRender: 'remark' }
					},
				]
			} else if (vs == 'orderMaterialCommon') {
				return [
					{
						title: '序号', width: '80px',
						customRender: (text, record, index) => `${index + 1}`
					},
					...this.columnsMaterialProperty,
					{
						title: '操作',
						width: '150px',
						scopedSlots: { customRender: 'actionCommon' }
					}
				]
			} else if (vs == 'packingInProductionOrder') {
				return [
					{
						title: '序号', width: '80px',
						customRender: (text, record, index) => `${index + 1}`
					},
					{
						title: '料号',
						dataIndex: 'materialCode'
					},
					{
						title: '名称',
						dataIndex: 'materialName'
					},
					{
						title: '订单号',
						dataIndex: 'orderNumber',
						ellipsis: true
					},
					{
						title: '出库数量',
						dataIndex: 'completedNumber'
					},
					{
						title: '备注',
						dataIndex: 'remark',
						ellipsis: true,
						scopedSlots: { customRender: 'remark' }
					},
					{
						title: '状态',
						dataIndex: 'executeStatus',
						customRender: (text, record, index) => {
							let es = this.$util.findExecuteStatusById(text)
							return es ? es.name : '未知状态'
						}
					}
				]
			} else {
				return []
			}
		},
		columnsMaterialProperty() {
			let result = [
				{
					title: '名称',
					dataIndex: 'materialName'
				},
				{
					title: '订单号',
					dataIndex: 'orderNumber',
					ellipsis: true
				},
				{
					title: '订单类型',
					dataIndex: 'orderType',
					customRender: (text, record, index) => {
						let otEnum = this.$util.findOrderTypeById(text)
						return otEnum ? otEnum.name : '未知类型'
					}
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber',
					scopedSlots: { customRender: 'materialModelNumber' }
				},
				{
					title: '图片',
					dataIndex: 'image',
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '需求数量',
					dataIndex: 'number'
				},
				{
					title: '已入库数量',
					dataIndex: 'completedNumber'
				},
				{
					title: '状态',
					dataIndex: 'executeStatus',
					customRender: (text, record, index) => {
						let es = this.$util.findExecuteStatusById(text)
						return es ? es.name : '未知状态'
					}
				},
				{
					title: '备注',
					dataIndex: 'remark',
					ellipsis: true,
					scopedSlots: { customRender: 'remark' }
				},
			]

			if (!this.extra) {
				return result
			}

			if (this.extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.material.id) {
				result = [
					{
						title: '原料编号',
						dataIndex: 'materialCode'
					},
					{
						title: '原料名称',
						dataIndex: 'materialName'
					},
					{
						title: '规格',
						dataIndex: 'materialModelNumber',
						scopedSlots: { customRender: 'materialModelNumber' }
					},
					{
						title: '图片',
						dataIndex: 'image',
						scopedSlots: { customRender: 'image' }
					},
					{
						title: '需求数量',
						dataIndex: 'number'
					},
					{
						title: '已入库数量',
						dataIndex: 'completedNumber'
					},
					{
						title: '备注',
						dataIndex: 'remark',
						ellipsis: true,
						scopedSlots: { customRender: 'remark' }
					},
					{
						title: '状态',
						dataIndex: 'executeStatus',
						customRender: (text, record, index) => {
							let es = this.$util.findExecuteStatusById(text)
							return es ? es.name : '未知状态'
						}
					},
				]
			} else if (this.extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.product.id) {
				result = [
					{
						title: '产品编号',
						dataIndex: 'materialCode'
					},
					{
						title: '产品名称',
						dataIndex: 'materialName'
					},
				]
			} else if (this.extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.packing.id) {
				result = [
					{
						title: '包材编号',
						dataIndex: 'materialCode'
					},
					{
						title: '包材名称',
						dataIndex: 'materialName'
					},
					{
						title: '规格',
						dataIndex: 'materialModelNumber',
						scopedSlots: { customRender: 'materialModelNumber' }
					},
					{
						title: '尺寸',
						dataIndex: 'extend1',
						scopedSlots: { customRender: 'extend1' }
					},
					{
						title: '图片',
						dataIndex: 'image',
						scopedSlots: { customRender: 'image' }
					},
					{
						title: '备注',
						dataIndex: 'remark',
						ellipsis: true,
						scopedSlots: { customRender: 'remark' }
					},
					{
						title: '需求数量',
						dataIndex: 'number'
					},
					{
						title: '已入库数量',
						dataIndex: 'completedNumber'
					}
				]
			} else if (this.extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.cable.id) {
				result = [
					{
						title: '线缆编号',
						dataIndex: 'materialCode'
					},
					{
						title: '线缆名称',
						dataIndex: 'materialName'
					},
					{
						title: '规格',
						dataIndex: 'materialModelNumber',
						scopedSlots: { customRender: 'materialModelNumber' }
					},
					{
						title: '颜色',
						dataIndex: 'extend3',
						scopedSlots: { customRender: 'extend3' }
					},
					{
						title: '图片',
						dataIndex: 'image',
						scopedSlots: { customRender: 'image' }
					},
					{
						title: '需求数量',
						dataIndex: 'number'
					},
					{
						title: '备注',
						dataIndex: 'remark',
						ellipsis: true,
						scopedSlots: { customRender: 'remark' }
					},
					{
						title: '已入库数量',
						dataIndex: 'completedNumber'
					}
				]
			}
			return result
		}
	},
	methods: {
		show(record, extra) {
			console.log(record, extra);

			this.visible = true
			this.emsOrder = record
			this.queryParam = {}
			if (extra) {
				this.queryParam = Object.assign({}, extra)
				this.title = `${extra.title}（${record.orderNumber}）`
				this.viewState = extra.viewState
				this.extra = extra
				this.queryParam.materialType = extra.materialType
			}

			if (record) {
				this.queryParam.orderId = record.orderId
				this.queryParam.sourceOrderMaterialId = record.sourceOrderMaterialId
			}
			this.queryParam.pageSize = -1
			setTimeout(() => {
				this.handleOk()
				this.$refs.table.clearSelected()
			}, 100)
		},
		del(record) {
			del(record).then((res) => {
				if (res.success) {
					this.$message.success('删除成功')
					this.$refs.table.refresh()
				} else {
					this.$message.error('删除失败：' + res.message)
				}
			}).catch((err) => {
				this.$message.error('删除错误：' + err.message)
			})
		},
		toggleAdvanced() {
			this.advanced = !this.advanced
		},
		handleOk() {
			this.$refs.table.refresh()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		handleSubmit() {
		},
		handleCancel() {
			this.visible = false
			this.$refs.table.clearSelected()
		},
		onEmsMaterialIndex1Selected(materialRow) {
			// console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
			// debugger
			let { materialId, materialName, materialCode, materialType, costPrice } = materialRow
			// 需要调用接口往订单中添加物料
			let _emsOrder = Object.assign({}, this.emsOrder)
			_emsOrder.orderMaterials = []
			let orderMaterial = {
				orderMaterialId: '',
				orderId: _emsOrder.orderId,
				bomId: '0',  // 单独选择原料时没有BOMID
				materialId: materialId,
				number: 1,
				completedNumber: 0,
				executeStatus: '0',
				executeProgress: '0',
				status: '0',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
			}
			_emsOrder.orderMaterials.push(orderMaterial)
			add(orderMaterial).then(res => {
				if (res.success) {
					this.$message.success('新增成功')
					// this.handleCancel()
					// this.$emit('ok', values)
					this.$refs.table.refresh()
				} else {
					this.$message.info('新增失败：' + res.message)
				}
			})
			// 然后刷新table控件
		},
		imageURLFormat(text) {
			return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${this.token}`
		},
		handleCompleteProduction() {
			this.confirmLoading = true
			let rows = this.selectedRows.filter(value => value.thisCompleteNumber > 0).map(value => {
				return {
					orderMaterialId: value.orderMaterialId,
					number: value.thisCompleteNumber
				}
			})
			if (rows.length == 0) {
				this.$message.error('错误：请选择产品并填写数量')
				this.confirmLoading = false
				return
			}

			let parameter = {
				orderId: this.emsOrder.orderId,
				orderType: this.emsOrder.orderType,
				orderMaterials: rows
			}
			handleProductionOrderProductComplete(parameter).then(res => {
				if (res.success) {
					// 有Bug,虽然表格数据刷新了,但实际上数字控件的值还是之前输入的.需要修改一下
					this.$message.success('操作成功')
					this.$emit('ok')
					this.handleCancel()
					this.confirmLoading = false
				} else {
					this.$message.error(res.message)
				}
			}).catch(reason => {
				this.$message.error(reason)
				this.confirmLoading = false
			})
		}
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
